package com.jhj.common.interceptor;

import static com.jhj.common.constants.CookieConstants.LOGIN_STATUS;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jhj.common.util.JhjEncryptUtil;
import com.jhj.common.util.JhjResponseUtil;
import com.jhj.common.util.JhjStringUtil;

public class JhjLoginInterceptor extends HandlerInterceptorAdapter {
    private String loginUrl;
    
    /**
     * loginUrl登录请求链接<br>
     * http://passport.jhjhome.com/login?retrunPath=
     * http://base.jhjhome.com/man/login?rp=
     * 
     * @param loginUrl
     */
    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Boolean loginStatus = (Boolean) request.getAttribute(LOGIN_STATUS);
        if (loginStatus == null || false == loginStatus) {
            
            String requestType = request.getHeader("X-Requested-With"); 
            if("XMLHttpRequest".equalsIgnoreCase(requestType)){
                //ajax请求
                Map<String, Object> result = new HashMap<String, Object>();
                result.put("status", "ERROR");
                result.put("data", "未授权访问");
                JhjResponseUtil.responseJson(response, result);
                return false;
            }
            // 未登录
            String requestUrl = request.getRequestURL().toString();
            
            String queryString = request.getQueryString();
            if (JhjStringUtil.isNotEmpty(queryString)) {
                requestUrl += "?" + queryString;
            }
            String currentPath = JhjEncryptUtil.urlEncode(requestUrl);
            response.sendRedirect(loginUrl + currentPath);
            return false;
        }
        
        // 登录用户
        return super.preHandle(request, response, handler);
    }
}
